package com.cskaoyan.common; /**
 * @Description
 * @Author zoe ling
 * @Date 2024/5/25
 */

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.util.JacksonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class CommonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 反射的业务代码是不是也要调整一下？ 调整获取的方法，和调用方法传入的参数
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            // 方法名后面要继续增加参数：方法的参数类型和顺序
            Method method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            Object result = method.invoke(this, req, resp);
            if (result instanceof BaseRespVo) {
                resp.setContentType("application/json;charset=utf-8");
                String jsonStr = JacksonUtil.write(result);
                resp.getWriter().println(jsonStr);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
